import 'dart:convert';
import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:sui_shou_pai/module/effect.dart';
import 'package:sui_shou_pai/network/http_config.dart';
import 'package:sui_shou_pai/network/http_request.dart';
import 'package:sui_shou_pai/record/image_widget.dart';
import 'package:sui_shou_pai/record/record_detail.dart';
import 'package:sui_shou_pai/record/record_entity/photo_record_entity.dart';
import 'package:sui_shou_pai/utils/storage_util.dart';

class RecordCardList extends StatefulWidget {
  List<PhotoRecordEntity> photoRecordEntityList;

  Function callback;

   RecordCardList({Key key, this.photoRecordEntityList,Function callback}) : super(key: key);

  @override
  _RecordCardListState createState() => _RecordCardListState();
}

class _RecordCardListState extends State<RecordCardList> {
  // 图片字符串拼接
  String imageSplit(String image) {
    List<String> imageList = image.split(',');
    if (imageList.isNotEmpty) {
      return imageList[0];
    } else
      return null;
  }
  List<PhotoRecordEntity> plist = [];
  Future<void> getNewData() async {
    plist.clear();
    HttpRequest.request("$BASE_URL/photo-record/getsortPhotoRecordList",
        method: "GET", token: await StorageUtil.getStringItem("token"))
        .then((value) {
      var data = jsonDecode(value.toString());
      List<dynamic> res = data['result'];
      for (int i = 0; i < res.length; i++) {
        PhotoRecordEntity photoRecordEntity =
        PhotoRecordEntity.fromJson(res[i]);
        plist.add(photoRecordEntity);
      }
      setState(() {
        widget.photoRecordEntityList.clear();
        if (plist.isNotEmpty) {
          for (int i = 0; i < plist.length; i++) {
            widget.photoRecordEntityList.add(plist[i]);
          }
          print("------record_card_list---"+ widget.photoRecordEntityList.toString());
        }
      });
    });
  }
  // 删除一条记录
  Future<void> deleteRecord(int id) {
    Future.delayed(Duration(milliseconds: 500), () async{
      HttpRequest.request(
          "$BASE_URL/photo-record/deletePhotoRecord/$id",
          method: "POST",
          token: await StorageUtil.getStringItem("token")
      ).then((value) {
      print("--------getNewData-");
      getNewData();
      //widget.callback(true);
      });
    });
  }


  @override
  Widget build(BuildContext context) {
    return GridView.count(
      crossAxisSpacing: 16,
      mainAxisSpacing: 16,
      padding: EdgeInsets.all(16),
      crossAxisCount: 2,
      childAspectRatio: 0.75,
      // 比如2.0，就是 宽/高=2
      children: getWidgetList(context),
    );
  }

  List<String> getDataList() {
    List<String> list = [];
    for (int i = 0; i < widget.photoRecordEntityList.length; i++) {
      list.add(i.toString());
    }
    return list;
  }

  List<Widget> getWidgetList(BuildContext context) {
    return getDataList()
        .map((item) => getItemContainer(item, context))
        .toList();
  }

  Widget getStatus(int index) {
    var statusColor;
    var title;
    if (widget.photoRecordEntityList[index].status.isNotEmpty) {
      if (widget.photoRecordEntityList[index].status == "1") {
        statusColor = Colors.greenAccent;
        title = "已通过";
      } else if (widget.photoRecordEntityList[index].status == "2") {
        statusColor = Colors.yellowAccent;
        title = "执行中";
      } else {
        statusColor = Colors.redAccent;
        title = "已提交";
      }
    }
    return Container(
        alignment: Alignment.center,
        height: 26,
        width: 56,
        decoration:
            BoxDecoration(borderRadius: borderRadiusAll4(), color: statusColor),
        child: Center(
            child: Text(
          title,
          style: TextStyle(
            color: Colors.black54,
          ),
        )));
  }

  Widget getItemContainer(String item, BuildContext context) {
    var index = int.parse(item);
    return Container(
        decoration: BoxDecoration(
          color: Colors.white,
          boxShadow: [shadowOffsetY2Deeper()],
          borderRadius: borderRadiusAll8(),
        ),
        child: ClipRRect(
          borderRadius: borderRadiusAll8(),
          child: Column(
            children: <Widget>[
              Expanded(
                child: GestureDetector(
                  child: Container(
                      child: Stack(
                    children: <Widget>[
                      ConstrainedBox(
                        constraints: const BoxConstraints.expand(),
                        child: ImageWidget(
                            url: imageSplit(
                                widget.photoRecordEntityList[index].image)),
                      ),
                      Container(
                          alignment: Alignment.topRight,
                          padding: EdgeInsets.all(12),
                          child: getStatus(index)),
                      Container(
                        alignment: Alignment.bottomCenter,
                        child: ClipRect(
                          child: BackdropFilter(
                            filter:
                                ImageFilter.blur(sigmaX: 16.0, sigmaY: 16.0),
                            child: Container(
                              color: Colors.white70,
                              height: 95,
                              padding: EdgeInsets.all(10),
                              child: Center(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    Text(
                                      widget
                                          .photoRecordEntityList[index].content,
                                      maxLines: 1,
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                          fontSize: 18.0,
                                          fontWeight: FontWeight.bold),
                                    ),
                                    SizedBox(
                                      height: 6.0,
                                    ),
                                    Row(
                                      children: <Widget>[
                                        Icon(
                                          Icons.perm_identity_outlined,
                                          size: 16,
                                          color: Colors.black54,
                                        ),
                                        SizedBox(
                                          width: 4.0,
                                        ),
                                        Text(
                                          widget.photoRecordEntityList[index]
                                              .publisherName,
                                          maxLines: 1,
                                          overflow: TextOverflow.ellipsis,
                                          style: TextStyle(
                                            fontSize: 14,
                                          ),
                                        ),
                                      ],
                                    ),
                                    SizedBox(
                                      height: 6.0,
                                    ),
                                    Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceBetween,
                                      children: <Widget>[
                                        Row(
                                          children: <Widget>[
                                            Icon(
                                              Icons.access_time_rounded,
                                              size: 16,
                                              color: Colors.black54,
                                            ),
                                            SizedBox(
                                              width: 4.0,
                                            ),
                                            Text(
                                              widget
                                                  .photoRecordEntityList[index]
                                                  .updateTime,
                                              maxLines: 1,
                                              style: TextStyle(
                                                fontSize: 14,
                                              ),
                                            ),
                                          ],
                                        ),
                                        Row(
                                          children: <Widget>[
                                            Icon(
                                              Icons.location_on_outlined,
                                              size: 16,
                                              color: Colors.black54,
                                            ),
                                            SizedBox(
                                              width: 4.0,
                                            ),
                                            Text(
                                              widget
                                                  .photoRecordEntityList[index]
                                                  .location,
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                              style: TextStyle(
                                                fontSize: 14,
                                              ),
                                            )
                                          ],
                                        ),
                                      ],
                                    ),
                                  ],
                                  //style: Theme.of(context).textTheme.display3,
                                ),
                              ),
                            ),
                          ),
                        ),
                      )
                    ],
                  )),
                  onTap: () {
                    Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => RecordDetail(photoRecordEntity: widget.photoRecordEntityList[index]),))
                                // settings: RouteSettings(
                                //     arguments:
                                //         widget.photoRecordEntityList[index])))
                        .then((value) {
                          print("-------页面跳出---------");
                          if(mounted){
                            List<String> l = value.toString().split(' ');
                            print("------List--"+ l.toString());
                            print("------ListLengeth--"+ l.length.toString());
                            if (l.length > 1){
                              if (l[1].isNotEmpty && l[1] == "删除"){
                                print("------List--"+ l[0].toString());
                                deleteRecord(int.parse(l[0]));
                                //widget.callback(true);
                                getNewData();
                                Fluttertoast.showToast(
                                    msg: "删除成功",
                                    toastLength: Toast.LENGTH_SHORT,
                                    gravity: ToastGravity.BOTTOM);
                          }
                            }
                          }
                      //print("-------------列表-----value:$value");
                    });
                  },
                ),
              )
            ],
          ),
        ));
  }
}
